package com.partner.boot.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.partner.boot.common.Result;
import com.partner.boot.entity.Role;
import com.partner.boot.entity.User;
import com.partner.boot.service.IRoleService;
import com.partner.boot.service.IUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
* <p>
*  前端控制器
* </p>
*
* @author 菜牙买菜
* @since 2022-12-07
*/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @ApiOperation(value = "新增用户信息")
    @PostMapping
    // 权限校验：必须具有指定权限才能进入该方法
    @SaCheckPermission("user.add")
    public Result save(@RequestBody User user) {
        userService.saveUser(user);
        return Result.success();
    }

    @ApiOperation(value = "修改用户信息")
    @PutMapping()
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        userService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(userService.findAll());
    }

    @GetMapping("/getUser")
    public Result getUser() {
        return Result.success(userService.getUser());
    }

    @GetMapping("/checkPass")
    public Result checkPass(@RequestParam Integer id, @RequestParam String password) {
        boolean result = userService.checkPass(id, password);
        return Result.success(result);
    }

    @GetMapping("/savePass")
    public Result savePass(@RequestParam Integer id, @RequestParam String password) {
        boolean result = userService.savePass(id, password);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.findOne(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String username,
                           @RequestParam(defaultValue = "") String email,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByDesc("id");
        queryWrapper.like(!"".equals(username), "username", username);
        queryWrapper.like(!"".equals(email), "email", email);
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        page.getRecords().forEach(v -> { // 根据用户角色唯一标识查询角色信息，并赋值给用户
            v.setRole(roleService.getOne(new QueryWrapper<Role>().eq("flag",v.getRoleFlag())));
        });
        return Result.success(page);
    }

    /*
    *
    * 根据用户名查询用户信息
    * */
    @GetMapping("/getName")
    public Result findPage(@RequestParam(defaultValue = "") String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);
        List<User> user = userService.list(queryWrapper);
        return Result.success(user);
    }

    /*
     *
     * 根据用户名查询用户信息
     * */
    @GetMapping("/getUserByUid")
    public Result getUserByUid(@RequestParam(defaultValue = "") String uid) {
        User user = userService.getOne(new QueryWrapper<User>().eq("uid", uid));
        return Result.success(user);
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("User信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
    * excel 导入
    * @param file
    * @throws Exception
    */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<User> list = reader.readAll(User.class);

//        userService.saveBatch(list);
        for (User user : list) {
            userService.saveUser(user);
        }
        return Result.success();
    }

}
